package edu.whut.mall.user.controller;


import edu.whut.mall.common.api.ResponseMap;
import edu.whut.mall.common.enums.FileType;
import edu.whut.mall.pojo.mapper.FileMapper;
import edu.whut.mall.common.service.IFdfsService;
import edu.whut.mall.pojo.model.File;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/fileManage")
@Slf4j
@Api(tags = {"文件管理"}, description = "文件管理", produces = MediaType.APPLICATION_JSON_VALUE)
public class FileManageController {

//    @Resource
//    private IFileManageService fileManageService;

    @Resource
    private IFdfsService fdfsService;

    @Resource
    private FileMapper fileMapper;


//    @ApiOperation(value = "上传文件到数据库", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "url", value = "url", paramType = "form", dataType = "string"),
//    })
//    @RequestMapping(value = "/addFile", method = RequestMethod.POST)
//    public Map uploadAndroidAPK(HttpServletRequest request, String url) throws Exception {
//        ResponseMap map = ResponseMap.getInstance();
//        File file = null;
//        if (url != null) {
//            file = fileManageService.addOneFile(url);
//        }
//        return map.putValue(file, "成功！");
//    }
//
//    @RequestMapping(value = "/getOneFile", method = RequestMethod.POST)
//    public Map getOneFile(HttpServletRequest request, int id) throws Exception {
//        ResponseMap map = ResponseMap.getInstance();
//        FileVo result = fileManageService.getOneFile(id);
//        if (null == result) {
//            return map.putFailure("获取失败", -1);
//        }
//        return map.putValue(result, "获取成功");
//    }
//
//
//    @ApiOperation("获取文件列表")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "current", value = "当前页数", paramType = "form", dataType = "int", required = true),
//            @ApiImplicitParam(name = "size", value = "当前页面显示记录数", paramType = "form", dataType = "int", required = true),
//            @ApiImplicitParam(name = "orderBy", value = "排序依据，例如:create_time", paramType = "form", dataType = "string", required = true),
//            @ApiImplicitParam(name = "asc", value = "排序规则，递增true或递减false", paramType = "form", dataType = "boolean")
//    })
//    @RequestMapping(value = "/getFilePage", method = RequestMethod.POST)
//    public Map getFilePage(HttpServletRequest request, int current, int size, String orderBy, Boolean asc,
//                           Integer id, String url, Integer isDeleted) throws Exception {
//        ResponseMap map = ResponseMap.getInstance();
//        Page<FileVo> page = fileManageService.getFilePage(current, size, orderBy, asc, id, url, isDeleted);
//        return map.putPage(page, "获取成功");
//    }
//
//
//    @ApiOperation("多文件上传(文件最大为1000MB)")
//    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
//    public Map uploadFile(HttpServletRequest request1, MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
//        log.info("开始文件上传");
//        ResponseMap map = ResponseMap.getInstance();
//        List<NameValuePair> additionalMap = new ArrayList<>();
//        Iterator<String> fileNames = request.getFileNames();
//        while (fileNames.hasNext()) {
//            String fileName = fileNames.next();//file
//            List<MultipartFile> files = request.getFiles(fileName);
//            for (MultipartFile file : files) {
//                if (file != null && file.getSize() > 0) {
//                    additionalMap.add(new BasicNameValuePair(fileName, FileUtil.upload("1", file)));
//
//                } else {
//                    additionalMap.add(new BasicNameValuePair(fileName, ""));
//                }
//            }
//        }
//
//        return map.putList(additionalMap, "成功上传");
//    }
//
//    @ApiOperation("单个文件上传(文件最大为1000MB)")
//    @RequestMapping(value = "/uploadOneFile", method = RequestMethod.POST)
//    public Map uploadOneFile(HttpServletRequest request1, MultipartHttpServletRequest request, MultipartFile multipartFile) throws Exception {
//        log.info("开始文件上传");
//        ResponseMap map = ResponseMap.getInstance();
//        List<NameValuePair> additionalMap = new ArrayList<>();
//        Iterator<String> fileNames = request.getFileNames();
//        while (fileNames.hasNext()) {
//            String fileName = fileNames.next();//file
//            List<MultipartFile> files = request.getFiles(fileName);
//            for (MultipartFile file : files) {
//                if (file != null && file.getSize() > 0) {
//                    additionalMap.add(new BasicNameValuePair(fileName, FileUtil.upload("1", file)));
//
//                } else {
//                    additionalMap.add(new BasicNameValuePair(fileName, ""));
//                }
//            }
//        }
//
//        return map.putList(additionalMap, "成功上传");
//    }
//
//    @ApiOperation("上传图片(返回原始图片url和压缩图片url)")
//    @RequestMapping(value = "/uploadOneImage", method = RequestMethod.POST)
//    public Map uploadeFile(HttpServletRequest request1, MultipartHttpServletRequest request, MultipartFile multipartFile) throws Exception {
//        log.info("开始文件上传");
//        ResponseMap map = ResponseMap.getInstance();
//        List<NameValuePair> additionalMap = new ArrayList<>();
//        Iterator<String> fileNames = request.getFileNames();
//        while (fileNames.hasNext()) {
//            String fileName = fileNames.next();//file
//            List<MultipartFile> files = request.getFiles(fileName);
//            for (MultipartFile file : files) {
//                if (file != null && file.getSize() > 0) {
//                    additionalMap.add(new BasicNameValuePair(fileName, FileUtil.upload("1", file)));
//                    //判断返回文件类型，是否为缩略图
//                    if (file.getContentType() != null && file.getContentType().startsWith("image/")) {
//                        //判断返回文件类型，是否为缩略图
//                        ByteArrayOutputStream out = new ByteArrayOutputStream();
//                        //压缩图片
//                        Thumbnails.of(new ByteArrayInputStream(file.getBytes()))
//                                //.size(256, 256)
//                                .scale(0.7f)
//                                .toOutputStream(out);
//                        additionalMap.add(new BasicNameValuePair(fileName + "Thumb", FileUtil.upload("1", file, out)));
//                    }
//
//                } else {
//                    additionalMap.add(new BasicNameValuePair(fileName, ""));
//                }
//            }
//        }
//
//        return map.putList(additionalMap, "成功上传");
//    }
//
//
//    @RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "id", paramType = "form", dataType = "int", required = true)
//    })
//    public Map deleteFile(HttpServletRequest request, int id) throws Exception {
//        ResponseMap map = ResponseMap.getInstance();
//        fileManageService.deleteFile(id);
//
//        return map.putValue("删除成功");
//    }
//
//    //自动批量物理删除fastdfs文件
//    @ApiOperation("删除最近100条未被删除的记录")
//    @RequestMapping(value = "/deleteFiles", method = RequestMethod.POST)
//    public Map deleteFiles(HttpServletRequest request) throws Exception {
//        ResponseMap map = ResponseMap.getInstance();
//        fileManageService.deleteFiles();
//        return map.putValue("删除成功");
//    }

    //    @ApiOperation("Fastdfs文件上传测试")
//    @RequestMapping(value = "/test",method = RequestMethod.POST)
//    public Map test(HttpServletRequest request){
//        ResponseMap map = ResponseMap.getInstance();
//        String temp1 = request.getParameter("file");
//        String temp2 = request.getParameter("fileThumb");
//        log.info("temp1: = "+temp1);
//        log.info("temp2: = "+temp2);
//        List<String> list = new ArrayList<>();
//        list.add(temp1);
//        list.add(temp2);
//        return map.putValue(list,"上传成功");
//    }
    @ApiOperation("用户批量上传文件")
    @PostMapping(value = "/uploadFile")
    public Map<String,Object> uploadFile(MultipartHttpServletRequest request) throws Exception {
        ResponseMap map = ResponseMap.getInstance();
        Iterator<String> fileNames = request.getFileNames();
        List<String> urls = new ArrayList<>();
        while (fileNames.hasNext()) {
            String fileName = fileNames.next();//file
            List<MultipartFile> files = request.getFiles(fileName);
            for (MultipartFile file : files) {
                String url = fdfsService.upload(file);
                File fileNew = new File(url, new Date(), false, FileType.图片);
                fileMapper.insert(fileNew);
                urls.add(url);
            }
        }
        return map.putValue(urls, "上传文件成功");
    }


    @ApiOperation("用户上传单个文件")
    @PostMapping(value = "/uploadFileOne")
    public Map<String,Object> uploadFileOne( HttpServletRequest request,MultipartFile file) throws Exception {
        ResponseMap map = ResponseMap.getInstance();
        String result = fdfsService.upload(file);
        File fileNew = new File(result, new Date(), false, FileType.图片);
        fileMapper.insert(fileNew);
        return map.putValue(result, "上传文件成功");
    }
}